package com.jinsp.networklibrary.util;

import android.util.Base64;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Created by luoshuai on 1/15/22
 * <p>
 * BASE64算法加解密
 */
public class BASE64Utils {

    /**
     * 加密字符串
     *
     * @param targetString 目标字符串
     * @param charset      字符串编码
     * @return 加密后的字符串
     */
    public static String encryptString(String targetString, Charset charset) {
        if (targetString != null && targetString.length() > 0) {
            if (charset == null) {
                charset = StandardCharsets.UTF_8;
            }
            byte[] encryptByteArray = encryptByteArray(targetString.getBytes(charset));
            return new String(encryptByteArray, charset);
        }
        return null;
    }

    /**
     * 解密字符串
     *
     * @param targetString 目标字符串
     * @param charset      字符串编码
     * @return 解密后的字符串
     */
    public static String decryptString(String targetString, Charset charset) {
        if (targetString != null && targetString.length() > 0) {
            if (charset == null) {
                charset = StandardCharsets.UTF_8;
            }
            byte[] decryptByteArray = decryptByteArray(targetString.getBytes(charset));
            return new String(decryptByteArray, charset);
        }
        return null;
    }

    /**
     * 使用BASE64加密字节数组
     *
     * @param targetByteArray 目标字节数组
     * @return 加密后的字节数组
     */
    public static byte[] encryptByteArray(byte[] targetByteArray) {
        if (targetByteArray == null || targetByteArray.length == 0) {
            return null;
        }
        //base64  NO_WRAP 过滤换行符  NO_PADDING 过滤结束符=   URL_SAFE 将+,/换成-,_
//        return Base64.encode(targetByteArray, Base64.NO_WRAP | Base64.NO_PADDING | Base64.URL_SAFE);
        return Base64.encode(targetByteArray, Base64.NO_WRAP);
    }

    /**
     * 解密字节数组
     *
     * @param targetByteArray 目标字节数组
     * @return 解密后的字节数组
     */
    public static byte[] decryptByteArray(byte[] targetByteArray) {
        if (targetByteArray == null || targetByteArray.length == 0) {
            return null;
        }
        return Base64.decode(targetByteArray, Base64.NO_WRAP);
//        return Base64.decode(targetByteArray, Base64.NO_WRAP | Base64.NO_PADDING | Base64.URL_SAFE);
    }
}
